package com.topnav.mc.system;

import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;

import com.js.lib.cache.Cache;
import com.sun.management.OperatingSystemMXBean;
import java.text.DecimalFormat;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import lombok.extern.slf4j.Slf4j;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 说明：系统监控
 * @类名: SystemMonitor
 *
 * @author   kenny
 * @Date	 2020年7月2日下午9:20:54
 */
//@Service
@Slf4j
@Deprecated
public class SystemMonitor implements ISystemMonitorService {

    //主控服务 器
    @Value("${control-server.api:control-server.api}")
    private String serverApi;
    @Value("${control-server.myname:control-server.myname}")
    private String serverName;
    @Resource(name="localCache")
    private Cache cache;

    @Override
    public void start() {
        ServerInfo serverInfo = new ServerInfo();

        if (cache.get("mySystemInfo") == null){
            cache.set("mySystemInfo",new MySystemInfo());
        }


        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            try {

                SystemInfo systemInfo = new SystemInfo();
                MySystemInfo mySystemInfo = (MySystemInfo)cache.get("mySystemInfo");

                OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
                MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
                // 椎内存使用情况
                MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();

                // 操作系统
                serverInfo.setOsName(System.getProperty("os.name"));
                // 总的物理内存


/*                String totalMemorySize = new DecimalFormat("#.##")
                        .format(osmxb.getTotalPhysicalMemorySize() / 1024.0 / 1024 / 1024) + "G";
                // 剩余的物理内存
                String freePhysicalMemorySize = new DecimalFormat("#.##")
                        .format(osmxb.getFreePhysicalMemorySize() / 1024.0 / 1024 / 1024) + "G";
                // 已使用的物理内存
                String usedMemory = new DecimalFormat("#.##").format(
                        (osmxb.getTotalPhysicalMemorySize() - osmxb.getFreePhysicalMemorySize()) / 1024.0 / 1024 / 1024) + "G";*/

/*
                mySystemInfo.setTotalMemorySize(osmxb.getTotalPhysicalMemorySize() / 1024.0 / 1024 / 1024);
                mySystemInfo.setFreeMemorySize(osmxb.getFreePhysicalMemorySize() / 1024.0 / 1024 / 1024);
                mySystemInfo.setUsesdMemorySize((osmxb.getTotalPhysicalMemorySize() - osmxb.getFreePhysicalMemorySize()) / 1024.0 / 1024 / 1024);

                serverInfo.setTotalMemorySize(new DecimalFormat("#.##").format(mySystemInfo.getTotalMemorySize())+"G");
                serverInfo.setFreeMemorySize(new DecimalFormat("#.##").format(mySystemInfo.getFreeMemorySize())+"G");
                serverInfo.setUsesdMemorySize(new DecimalFormat("#.##").format(mySystemInfo.getUsesdMemorySize())+"G");
*/
                // 获得线程总数
                ThreadGroup parentThread;
                for (parentThread = Thread.currentThread().getThreadGroup(); parentThread.getParent() != null; parentThread = parentThread.getParent()) {
                }
                int totalThread = parentThread.activeCount();
                serverInfo.setTotalThread(String.valueOf(totalThread));

                // 磁盘使用情况
                File[] files = File.listRoots();
                Long total=0L;
                Long used=0L;
                Long free=0L;
                for (File file : files) {
                    total += (long) (file.getTotalSpace() * 1.0 / 1024 / 1024 / 1024);
                    free += (long) (file.getFreeSpace() * 1.0 / 1024 / 1024 / 1024);
                }

                serverInfo.setTotalDisksize(new DecimalFormat("#.#").format(total)+"G");
                serverInfo.setFreeDisksize(new DecimalFormat("#.#").format(free)+"G");
                used = total - free;
                serverInfo.setUsedDisksize(new DecimalFormat("#.#").format(used)+"G");
                mySystemInfo.setTotalDisksize(total);
                mySystemInfo.setFreeDisksize(free);
                mySystemInfo.setUsedDisksize(used);

                CentralProcessor processor = systemInfo.getHardware().getProcessor();
                long[] prevTicks = processor.getSystemCpuLoadTicks();
                TimeUnit.SECONDS.sleep(1);
                long[] ticks = processor.getSystemCpuLoadTicks();
                long nice = ticks[CentralProcessor.TickType.NICE.getIndex()]
                        - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
                long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()]
                        - prevTicks[CentralProcessor.TickType.IRQ.getIndex()];
                long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()]
                        - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];
                long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()]
                        - prevTicks[CentralProcessor.TickType.STEAL.getIndex()];
                long cSys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()]
                        - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
                long user = ticks[CentralProcessor.TickType.USER.getIndex()]
                        - prevTicks[CentralProcessor.TickType.USER.getIndex()];
                long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()]
                        - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
                long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()]
                        - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
                long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
                serverInfo.setCpuProcessorCount(String.valueOf(processor.getLogicalProcessorCount()));
                serverInfo.setCpuIdleRate(new DecimalFormat("#.##%").format(idle * 1.0 / totalCpu));
                serverInfo.setCpuUsedRate(new DecimalFormat("#.##%").format((cSys + user) * 1.0 / totalCpu));
                serverInfo.setServerName(serverName);


                mySystemInfo.setCpuUsedRate(Math.round((cSys + user) * 1.0 / totalCpu*10000)/100.0);
                mySystemInfo.setCpuIdleRate(100-mySystemInfo.getCpuUsedRate());
                //String resultstr = HttpUtil.doPost(serverApi,new Gson().toJson(serverInfo),null);
                System.err.println(serverInfo.toString());
                //log.info(serverInfo.toString());
            } catch (Exception e) {
                e.printStackTrace();
                log.error(serverInfo.toString());
            }
        }, 0, 60, TimeUnit.SECONDS);
    }
}

